﻿#pragma once

// 包含所需的头文件
#include <queue>
#include <stdint.h>
#include <thread>
#include <define.h>
#include <log_wapper.hpp>
#include <trader_api.h>
#include <define_types.hpp>
#include <params.hpp>
#include <condition_variable>
#include <../../api/CTP_V6.6.9_20220920/ThostFtdcTraderApi.h>
#include <dll_helper.hpp>

// ctp_api_trader 类
// 继承自 asyn_actual_trader（异步实际交易员）和 CThostFtdcTraderSpi（CTP 交易 SPI 接口实现类）
class ctp_api_trader : public asyn_actual_trader, public CThostFtdcTraderSpi
{
    // 订单操作类型枚举类
    enum class action_flag
    {
        AF_CANCEL = '0',    // 撤销
        AF_MODIFY = '3',    // 修改
    };

public:
    // 构造函数，初始化交易 API 对象
    ctp_api_trader(const std::shared_ptr<std::unordered_map<std::string, std::string>>& id_excg_map, const params& config) noexcept;

    // 析构函数，释放交易 API 资源
    virtual ~ctp_api_trader() noexcept;

    // trader_api 接口的实现
public:
    virtual bool login() noexcept override;                              // 登录
    virtual void logout() noexcept override;                            // 登出
    virtual bool is_usable() const noexcept override;                   // 检查是否可用
    virtual estid_t place_order(offset_type offset, direction_type direction, const code_t& code, uint32_t count, double_t price, order_flag flag) noexcept override; // 下单
    virtual bool cancel_order(estid_t estid) noexcept override;         // 撤单
    virtual uint32_t get_trading_day() const noexcept override;         // 获取交易日
    virtual std::shared_ptr<trader_data> get_trader_data() noexcept override; // 获取交易数据

    // CTP 交易接口实现
public:
    virtual void OnFrontConnected() noexcept override;                    // 连接成功回调
    virtual void OnFrontDisconnected(int nReason) noexcept override;      // 连接断开回调
    virtual void OnRspAuthenticate(CThostFtdcRspAuthenticateField* pRspAuthenticateField, CThostFtdcRspInfoField* pRspInfo, int nRequestID, bool bIsLast) noexcept override; // 认证回调
    virtual void OnRspUserLogin(CThostFtdcRspUserLoginField* pRspUserLogin, CThostFtdcRspInfoField* pRspInfo, int nRequestID, bool bIsLast) noexcept override; // 登录回调
    virtual void OnRspUserLogout(CThostFtdcUserLogoutField* pUserLogout, CThostFtdcRspInfoField* pRspInfo, int nRequestID, bool bIsLast) noexcept override; // 登出回调
    virtual void OnRspSettlementInfoConfirm(CThostFtdcSettlementInfoConfirmField* pSettlementInfoConfirm, CThostFtdcRspInfoField* pRspInfo, int nRequestID, bool bIsLast) noexcept override; // 结算确认回调
    virtual void OnRspOrderInsert(CThostFtdcInputOrderField* pInputOrder, CThostFtdcRspInfoField* pRspInfo, int nRequestID, bool bIsLast) noexcept override; // 订单插入回调
    virtual void OnRspOrderAction(CThostFtdcInputOrderActionField* pInputOrderAction, CThostFtdcRspInfoField* pRspInfo, int nRequestID, bool bIsLast) noexcept override; // 订单操作回调
    virtual void OnRspQryInvestorPosition(CThostFtdcInvestorPositionField* pInvestorPosition, CThostFtdcRspInfoField* pRspInfo, int nRequestID, bool bIsLast) noexcept override; // 查询持仓回调
    virtual void OnRspQryOrder(CThostFtdcOrderField* pOrder, CThostFtdcRspInfoField* pRspInfo, int nRequestID, bool bIsLast) noexcept override; // 查询订单回调
    virtual void OnRspError(CThostFtdcRspInfoField* pRspInfo, int nRequestID, bool bIsLast) noexcept override; // 错误响应回调
    virtual void OnRtnOrder(CThostFtdcOrderField* pOrder) noexcept override; // 订单状态变化回调
    virtual void OnErrRtnOrderInsert(CThostFtdcInputOrderField* pInputOrder, CThostFtdcRspInfoField* pRspInfo) noexcept override; // 订单插入错误回调
    virtual void OnErrRtnOrderAction(CThostFtdcOrderActionField* pOrderAction, CThostFtdcRspInfoField* pRspInfo) noexcept override; // 订单操作错误回调
    virtual void OnRtnInstrumentStatus(CThostFtdcInstrumentStatusField* pInstrumentStatus) noexcept override; // 合约状态变化回调

private:
    // 交易功能方法
    bool do_auth() noexcept;                    // 认证
    bool do_login() noexcept;                   // 登录
    bool do_logout() noexcept;                  // 登出
    bool query_positions(bool is_sync) noexcept; // 查询持仓
    bool query_orders(bool is_sync) noexcept;   // 查询订单
    void submit_settlement() noexcept;          // 提交结算确认

    // 工具方法：转换方向、偏移类型，生成和解析订单 ID，转换操作标志
    inline int convert_direction_offset(direction_type dir_type, offset_type offset_type) noexcept;
    inline direction_type wrap_direction_offset(TThostFtdcDirectionType dir_type, TThostFtdcOffsetFlagType offset_type) noexcept;
    inline int convert_offset_type(const code_t& code, uint32_t volume, offset_type offset, direction_type direction) noexcept;
    inline offset_type wrap_offset_type(TThostFtdcOffsetFlagType offset_type) noexcept;
    inline int convert_action_flag(action_flag action_flag) noexcept;
    inline estid_t generate_estid() noexcept;
    inline estid_t generate_estid(uint32_t front_id, uint32_t session_id, uint32_t order_ref) noexcept;
    inline void extract_estid(estid_t estid, uint32_t& front_id, uint32_t& session_id, uint32_t& order_ref) noexcept;
    inline uint32_t genreqid() noexcept; // 生成请求 ID

protected:
    // 成员变量
    CThostFtdcTraderApi* _td_api;                // CTP 交易 API 指针
    std::atomic<uint32_t> _reqid;                // 请求 ID 计数器
    std::string _front_addr;                     // 前置地址
    std::string _broker_id;                      // 经纪商 ID
    std::string _userid;                         // 用户 ID
    std::string _password;                       // 密码
    std::string _appid;                          // 应用 ID
    std::string _authcode;                       // 认证码
    std::string _product_info;                   // 产品信息

    uint32_t _front_id;                          // 前置编号
    uint32_t _session_id;                        // 会话编号
    std::atomic<uint32_t> _order_ref;            // 报单引用

    std::map<code_t, position_seed> _position_info; // 持仓信息
    entrust_map _order_info;                     // 订单信息

    bool _is_runing;                             // 是否正在运行
    std::mutex _mutex;                           // 互斥锁
    std::unique_lock<std::mutex> _process_mutex; // 进程互斥锁
    std::condition_variable _process_signal;     // 进程信号量
    std::atomic<bool> _is_in_query;              // 是否在查询
    bool _is_inited;                             // 是否初始化
    bool _is_connected;                          // 是否已连接
    std::atomic<bool> _is_sync_wait;             // 是否同步等待
    typedef CThostFtdcTraderApi* (*trader_creator)(const char*); // 定义交易 API 创建函数指针
    trader_creator _ctp_creator;                 // CTP 创建函数
    dll_handle _trader_handle;                   // 动态库句柄
};
